/**
 * @file Dashboard.jsx
 * @description 后台管理系统的控制面板页面组件，参考 dashboard.html 进行美化
 */
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Row, Col, Card, Table, Typography, Tag, Avatar, Space, List, Button } from 'antd';
import {
  DollarCircleTwoTone,
  ShoppingCartOutlined,
  TeamOutlined,
  BellTwoTone,
  AreaChartOutlined,
  CrownTwoTone,
  PlusCircleOutlined,
  CarryOutOutlined,
  LineChartOutlined,
  SoundOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
} from '@ant-design/icons';
import { Line } from '@ant-design/charts'; // 导入 Line 图表
import { fetchAllOrders } from '../store/ordersSlice';
import { fetchAllUsers } from '../store/usersSlice';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';

const { Title, Text } = Typography;

// --- 统计卡片组件 ---
const InfoCard = ({ title, value, description, icon, trend, trendColor, cardColor, onLinkClick, subDescription }) => {
  return (
    <Card
      hoverable
      variant="borderless"
      style={{
        borderRadius: '10px',
        boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
        backgroundColor: '#fff',
        height: '100%'
      }}
    >
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Text style={{ fontSize: '1.1em', fontWeight: 600, color: '#34495e' }}>{title}</Text>
          </Col>
          <Col>
            <Avatar size={40} icon={icon} style={{ backgroundColor: cardColor?.iconBg || '#e9ecef', color: cardColor?.iconColor || '#3498db' }} />
          </Col>
        </Row>
        <Text style={{ fontSize: '2em', fontWeight: 'bold', color: '#2c3e50', display: 'block' }}>{value}</Text>
        {subDescription && <Text type="secondary" style={{ fontSize: '0.9em', display: 'block', marginTop: '-10px', marginBottom: '5px'  }}>{subDescription}</Text>}
        {description && <Text type="secondary" style={{ fontSize: '0.9em' }}>{description}</Text>}
        {trend && trend !== 'N/A' && (
          <Text style={{ fontSize: '0.9em', color: trendColor, marginTop: '10px', display: 'block' }}>
            {trend.startsWith('+') ? <ArrowUpOutlined /> : <ArrowDownOutlined />} {trend}
          </Text>
        )}
        {trend === 'N/A' && (
          <Text style={{ fontSize: '0.9em', color: 'grey', marginTop: '10px', display: 'block' }}>
            昨日无数据
          </Text>
        )}
        {onLinkClick && (
             <Button type="link" onClick={onLinkClick} style={{ padding: 0, marginTop: '10px', fontSize: '0.9em', color: '#3498db' }}>
                 立即处理 &rarr;
            </Button>
        )}
      </Space>
    </Card>
  );
};


const Dashboard = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { orders, isLoading: ordersLoading } = useSelector((state) => state.orders);
  const { users, isLoading: usersLoading } = useSelector((state) => state.users);

  const [dashboardStats, setDashboardStats] = useState({
    totalSales: 0,
    todayOrdersCount: 0,
    todayNewUsers: 0,
    pendingTickets: 0,
    popularProducts: [],

    salesForTodayText: '¥0.00',
    salesTrend: 'N/A',
    salesTrendColor: 'grey',

    ordersForYesterdayText: '0 单',
    ordersTrend: 'N/A',
    ordersTrendColor: 'grey',

    usersForYesterdayText: '0 新用户',
    usersTrend: 'N/A',
    usersTrendColor: 'grey',

    salesTrendData: [], // 新增：用于存储过去30天销售趋势图表数据
  });

  useEffect(() => {
    dispatch(fetchAllOrders());
    dispatch(fetchAllUsers());
  }, [dispatch]);

  useEffect(() => {
    if (!orders || !users) {
        return;
    }

    const today = dayjs().startOf('day');
    const yesterday = dayjs().subtract(1, 'day').startOf('day');

    const cumulativeTotalSales = Array.isArray(orders) ? orders.reduce((sum, order) => sum + (order.totalAmount || 0), 0) : 0;

    const todayOrdersArray = Array.isArray(orders) ? orders.filter(order =>
        order.date && dayjs(order.date).isSame(today, 'day')
    ) : [];
    const salesForToday = todayOrdersArray.reduce((sum, order) => sum + (order.totalAmount || 0), 0);
    const ordersForTodayCount = todayOrdersArray.length;

    const todayUsersArray = Array.isArray(users) ? users.filter(user =>
        user.createdAt && dayjs(user.createdAt).isSame(today, 'day')
    ) : [];
    const newUsersForTodayCount = todayUsersArray.length;

    const yesterdayOrdersArray = Array.isArray(orders) ? orders.filter(order =>
        order.date && dayjs(order.date).isSame(yesterday, 'day')
    ) : [];
    const salesForYesterday = yesterdayOrdersArray.reduce((sum, order) => sum + (order.totalAmount || 0), 0);
    const ordersForYesterdayCount = yesterdayOrdersArray.length;

    const yesterdayUsersArray = Array.isArray(users) ? users.filter(user =>
        user.createdAt && dayjs(user.createdAt).isSame(yesterday, 'day')
    ) : [];
    const newUsersForYesterdayCount = yesterdayUsersArray.length;

    const calculateTrend = (current, previous) => {
        if (previous === 0) {
            if (current > 0) return { value: '+∞%', color: '#27ae60' };
            return { value: 'N/A', color: 'grey' };
        }
        if (current === 0 && previous > 0) {
             const percentage = -100;
              return {
                value: `${percentage.toFixed(1)}%`,
                color: '#c0392b',
            };
        }
        const percentage = ((current - previous) / previous) * 100;
        return {
            value: `${percentage > 0 ? '+' : ''}${percentage.toFixed(1)}%`,
            color: percentage >= 0 ? '#27ae60' : '#c0392b',
        };
    };

    const salesTrendStats = calculateTrend(salesForToday, salesForYesterday);
    const ordersTrendStats = calculateTrend(ordersForTodayCount, ordersForYesterdayCount);
    const usersTrendStats = calculateTrend(newUsersForTodayCount, newUsersForYesterdayCount);

    const productCounts = {};
    if (Array.isArray(orders)) {
        orders.forEach(order => {
        if (order.items && Array.isArray(order.items)) {
            order.items.forEach(item => {
            if (item && item.title) {
                productCounts[item.title] = (productCounts[item.title] || 0) + (item.qty || 0);
            }
            });
        }
        });
    }
    const sortedProducts = Object.entries(productCounts)
    .sort(([, qtyA], [, qtyB]) => qtyB - qtyA)
    .slice(0, 5)
    .map(([title, qty], index) => ({ rank: index + 1, name: title, sales: qty }));

    // --- 计算过去30天销售数据 ---
    const monthlySalesChartData = [];
    if (Array.isArray(orders) && orders.length > 0) {
        const thirtyDaysAgo = dayjs().startOf('day'); // Renaming for clarity in loop
        for (let i = 29; i >= 0; i--) {
            const currentDate = thirtyDaysAgo.subtract(i, 'day'); // Iterate from 29 days ago to today
            const dateStr = currentDate.format('YYYY-MM-DD');
            
            const salesOnDate = orders
                .filter(order => order.date && dayjs(order.date).isSame(currentDate, 'day'))
                .reduce((sum, order) => sum + (order.totalAmount || 0), 0);
            
            monthlySalesChartData.push({
                date: dateStr,
                sales: salesOnDate,
            });
        }
    }

    setDashboardStats(prev => ({ // Use functional update to ensure all parts of state are preserved
        ...prev, // Spread previous state first
        totalSales: cumulativeTotalSales,
        todayOrdersCount: ordersForTodayCount,
        todayNewUsers: newUsersForTodayCount,
        // pendingTickets: 0, // Already set in initial state or handled elsewhere
        popularProducts: sortedProducts,

        salesForTodayText: `今日 ¥${salesForToday.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`,
        salesTrend: salesTrendStats.value,
        salesTrendColor: salesTrendStats.color,

        ordersForYesterdayText: `昨日 ${ordersForYesterdayCount} 单`,
        ordersTrend: ordersTrendStats.value,
        ordersTrendColor: ordersTrendStats.color,

        usersForYesterdayText: `昨日 ${newUsersForYesterdayCount} 新用户`,
        usersTrend: usersTrendStats.value,
        usersTrendColor: usersTrendStats.color,

        salesTrendData: monthlySalesChartData, // 更新图表数据
    }));

  }, [orders, users]);

  const recentOrdersData = orders && orders.length > 0
    ? [...orders]
        .sort((a, b) => new Date(b.date) - new Date(a.date))
        .slice(0, 4)
        .map(order => ({ ...order, key: order.orderId }))
    : [];


  const statusColorsHtml = {
    completed: { background: '#d4edda', color: '#155724' },
    pending: { background: '#fff3cd', color: '#856404' },
    shipped: { background: '#cce5ff', color: '#004085' },
    cancelled: { background: '#f8d7da', color: '#721c24' },
    processing: { background: '#d1e7dd', color: '#0f5132' }
  };

  const getStatusStyle = (status) => {
    if (typeof status !== 'string') {
        return { background: '#f0f0f0', color: '#555'};
    }
    let htmlStatusKey = status.toLowerCase();
    if (status === '处理中') htmlStatusKey = 'processing';
    if (status === '已完成') htmlStatusKey = 'completed';
    if (status === '已发货') htmlStatusKey = 'shipped';
    if (status === '已取消') htmlStatusKey = 'cancelled';

    return statusColorsHtml[htmlStatusKey] || { background: '#f0f0f0', color: '#555'};
  };

  const orderTableColumns = [
    { title: <Text strong>订单号</Text>, dataIndex: 'orderId', key: 'orderId', render: text => <Text strong style={{color: "#3498db"}}>{text}</Text> },
    { title: <Text strong>客户名称</Text>, dataIndex: ['shippingAddress', 'fullName'], key: 'customerName', render: (fullName) => fullName || 'N/A' },
    { title: <Text strong>订单金额</Text>, dataIndex: 'totalAmount', key: 'totalAmount', render: amount => `¥${typeof amount === 'number' ? amount.toFixed(2) : '0.00'}` },
    { title: <Text strong>下单时间</Text>, dataIndex: 'date', key: 'date', render: date => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : 'N/A' },
    {
      title: <Text strong>状态</Text>,
      dataIndex: 'status',
      key: 'status',
      render: status => {
        const styleToApply = getStatusStyle(status);
        return (
          <Tag style={{
            backgroundColor: styleToApply.background,
            color: styleToApply.color,
            borderColor: 'transparent',
            borderRadius: '12px',
            padding: '4px 8px',
            fontSize: '0.8em',
            fontWeight: 500,
          }}>
            {status || '未知'}
          </Tag>
        );
      }
    },
    { title: <Text strong>操作</Text>, key: 'action', render: (_, record) => <Button type="link" onClick={() => navigate(`/orders?orderId=${record.orderId}`)} style={{color:"#3498db", padding: 0}}>详情</Button> },
  ];

  const quickActionButtons = [
    { text: "添加新商品", icon: <PlusCircleOutlined />, onClick: () => toast.info("“添加新商品”功能暂未开放") },
    { text: "处理退款", icon: <CarryOutOutlined />, onClick: () => toast.info("“处理退款”功能暂未开放") },
    { text: "销售报表", icon: <LineChartOutlined />, onClick: () => toast.info("“销售报表”功能暂未开放") },
    { text: "发布公告", icon: <SoundOutlined />, onClick: () => toast.info("“发布公告”功能暂未开放") },
  ];

  // --- 图表配置 ---
  const salesChartConfig = {
    data: dashboardStats.salesTrendData,
    xField: 'date',
    yField: 'sales',
    height: 300,
    smooth: true, // 使线条平滑
    xAxis: {
      title: null, // 不显示X轴标题
      label: {
        autoRotate: true,
        autoHide: true,
        formatter: (text) => dayjs(text).format('MM-DD'), // 格式化日期显示
      },
    },
    yAxis: {
      title: null, // 不显示Y轴标题
      label: {
        formatter: (value) => `¥${(Number(value)/1000).toFixed(0)}k`, // 将Y轴标签简化，例如显示为 ¥1k, ¥2k
      },
    },
    tooltip: {
      title: (date) => dayjs(date).format('YYYY-MM-DD'), // 提示框标题显示完整日期
      formatter: (datum) => {
        return { name: '销售额', value: `¥${datum.sales.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}` };
      },
    },
    point: {
      size: 3,
      shape: 'circle',
      style: {
        fill: 'white',
        stroke: '#3498db',
        lineWidth: 1.5,
      },
    },
    lineStyle: {
      stroke: '#3498db',
      lineWidth: 2,
    },
    padding: 'auto', // 自动内边距
    theme: 'light', // 可以尝试 'dark' 或自定义主题
  };


  return (
    <div style={{ padding: '25px', backgroundColor: '#f4f7f9' }}>
      <Title level={2} style={{ marginBottom: '25px', color: '#2c3e50', fontWeight: 600 }}>
        仪表盘概览
      </Title>

      <Row gutter={[20, 20]} style={{ marginBottom: '25px' }}>
        <Col xs={24} sm={12} md={12} lg={6}>
          <InfoCard
            title="总销售额"
            value={`¥${dashboardStats.totalSales.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}`}
            subDescription={dashboardStats.salesForTodayText}
            icon={<DollarCircleTwoTone twoToneColor="#2ecc71" />}
            cardColor={{ iconBg: 'rgba(46, 204, 113, 0.1)', iconColor: '#2ecc71' }}
            trend={dashboardStats.salesTrend}
            trendColor={dashboardStats.salesTrendColor}
          />
        </Col>
        <Col xs={24} sm={12} md={12} lg={6}>
          <InfoCard
            title="今日订单"
            value={dashboardStats.todayOrdersCount.toString()}
            subDescription={dashboardStats.ordersForYesterdayText}
            icon={<ShoppingCartOutlined />}
            cardColor={{ iconBg: 'rgba(230, 126, 34, 0.1)', iconColor: '#e67e22' }}
            trend={dashboardStats.ordersTrend}
            trendColor={dashboardStats.ordersTrendColor}
            onLinkClick={() => navigate('/orders')}
          />
        </Col>
        <Col xs={24} sm={12} md={12} lg={6}>
          <InfoCard
            title="今日新增用户"
            value={dashboardStats.todayNewUsers.toString()}
            subDescription={dashboardStats.usersForYesterdayText}
            icon={<TeamOutlined />}
            cardColor={{ iconBg: 'rgba(155, 89, 182, 0.1)', iconColor: '#9b59b6' }}
            trend={dashboardStats.usersTrend}
            trendColor={dashboardStats.usersTrendColor}
            onLinkClick={() => navigate('/users')}
          />
        </Col>
        <Col xs={24} sm={12} md={12} lg={6}>
          <InfoCard
            title="待处理工单"
            value={dashboardStats.pendingTickets.toString()}
            description="客服待处理"
            icon={<BellTwoTone twoToneColor="#f1c40f" />}
            cardColor={{ iconBg: 'rgba(241, 196, 15, 0.1)', iconColor: '#f1c40f' }}
            onLinkClick={() => toast.info('工单功能暂未开放')}
          />
        </Col>
      </Row>

       <Row gutter={[20, 20]} style={{ marginBottom: '25px' }}>
        <Col xs={24} lg={16}>
          <Card
            title={<Text style={{ fontSize: '1.1em', fontWeight: 600, color: '#34495e' }}>销售趋势 (近30天)</Text>}
            variant="borderless"
            style={{ borderRadius: '10px', boxShadow: '0 4px 12px rgba(0,0,0,0.08)', backgroundColor: '#fff', height: '100%', paddingBottom: '10px' }} // Added paddingBottom
          >
            {ordersLoading ? (
                 <div style={{ height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#e9ecef', borderRadius: '8px'}}>
                    <Text type="secondary" style={{fontSize: '1.2em'}}>图表加载中...</Text>
                 </div>
            ) : dashboardStats.salesTrendData && dashboardStats.salesTrendData.length > 0 ? (
                <Line {...salesChartConfig} />
            ) : (
                <div style={{ height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: '#e9ecef', borderRadius: '8px'}}>
                    <Text type="secondary" style={{fontSize: '1.2em'}}>
                        <AreaChartOutlined /> 暂无销售数据生成图表
                    </Text>
                </div>
            )}
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card
            title={<Text style={{ fontSize: '1.1em', fontWeight: 600, color: '#34495e' }}>热门商品 Top 5</Text>}
            variant="borderless"
            style={{ borderRadius: '10px', boxShadow: '0 4px 12px rgba(0,0,0,0.08)', backgroundColor: '#fff', height: '100%' }}
          >
            <List
              itemLayout="horizontal"
              dataSource={dashboardStats.popularProducts}
              loading={ordersLoading || usersLoading} // popularProducts depend on orders
              renderItem={(item, index) => (
                <List.Item style={{padding: '10px 0', borderBottom: index === dashboardStats.popularProducts.length -1 ? 'none' : '1px solid #f0f0f0'}}>
                  <List.Item.Meta
                    avatar={<Text style={{fontSize: '1em', fontWeight: 'bold', color: '#3498db', marginRight: '15px', minWidth: '20px', textAlign: 'center'}}>{item.rank}</Text>}
                    title={<Text >{item.name}</Text>}
                    description={`${item.sales} 件售出`}
                  />
                </List.Item>
              )}
              style={{maxHeight: '300px', overflowY: 'auto'}}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[20, 20]} style={{ marginBottom: '25px' }}>
        <Col span={24}>
          <Card
            title={<Text style={{ fontSize: '1.1em', fontWeight: 600, color: '#34495e' }}>近期订单</Text>}
            extra={<Button type="link" onClick={() => navigate('/orders')} style={{color:"#3498db"}}>查看全部订单 &rarr;</Button>}
            variant="borderless"
            style={{ borderRadius: '10px', boxShadow: '0 4px 12px rgba(0,0,0,0.08)', backgroundColor: '#fff' }}
          >
            <Table
              columns={orderTableColumns}
              dataSource={recentOrdersData}
              pagination={false}
              loading={ordersLoading}
              style={{marginTop: '10px'}}
            />
          </Card>
        </Col>
      </Row>

      {/* <Row>
        <Col span={24}>
           <Card
            title={<Text style={{ fontSize: '1.1em', fontWeight: 600, color: '#34495e' }}>快捷操作</Text>}
            variant="borderless"
            style={{ borderRadius: '10px', boxShadow: '0 4px 12px rgba(0,0,0,0.08)', backgroundColor: '#fff' }}
          >
            <Row gutter={[15, 15]} style={{marginTop: '10px'}}>
              {quickActionButtons.map(action => (
                <Col xs={24} sm={12} md={6} key={action.text}>
                  <Button
                    type="primary"
                    icon={action.icon}
                    onClick={action.onClick}
                    block
                    size="large"
                    style={{
                        backgroundColor: '#3498db',
                        borderColor: '#3498db',
                        borderRadius: '6px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                    }}
                    onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = '#2980b9'; e.currentTarget.style.borderColor = '#2980b9';}}
                    onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = '#3498db'; e.currentTarget.style.borderColor = '#3498db';}}
                  >
                    <span style={{ marginLeft: action.icon ? '8px' : '0' }}>{action.text}</span>
                  </Button>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
      </Row> */}
    </div>
  );
};

export default Dashboard;